import {useEffect, useState} from 'react'
import './App.css'
import {lkMed} from "./main.tsx";
import Markdown from "react-markdown";
import { v4 as uuidv4 } from 'uuid';

function App() {
    const [messages, setMessages] = useState([])

    const [text, setText] = useState("")

    useEffect(() => {
    }, [])

    const chuckHandle = (chuck) => {
        if (chuck.content) {
            let msg = chuck
            setMessages(prevMessages => [...prevMessages, msg]);
        }

    }

    const sendMsg = async () => {
        //  甲硝唑和利托那韦之间的相互作用
        setText("")
        const sendMsg = {content: text}
        const stream0 = await lkMed.sendMsg(sendMsg)
        let msg = undefined
        for await (const chunk of stream0) {
            if (chunk?.content) {
                if (!msg) {
                    msg = { ...chunk, id: uuidv4() }; // 生成唯一ID
                    setMessages(prevMessages => [...prevMessages, msg]);
                } else {
                    msg.content += chunk.content;
                    setMessages(prevMessages => {
                        return prevMessages.map(m => m.id === msg.id ? { ...m, content: msg.content } : m)
                    });
                }
            } else {
                console.log(chunk, msg);
                msg = undefined
            }
        }
        console.log('sssss')
    }

    return (
        <>
            <div>
                {
                    messages.map((msg: any) => {
                        return <Markdown key={msg.id}>{msg.content}</Markdown>
                    })
                }
            </div>

            <div className="card">
                <input value={text} onChange={(e: any) => setText(e.target.value)}></input>
                <button onClick={() => sendMsg()}>发送</button>
            </div>
        </>
    )
}

export default App
